package com.yc.testupload;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@WebFilter("/*")
public class SessionFilter implements Filter {

    private static final Logger logger = LogManager.getLogger(SessionFilter.class);
    
    // 不需要登录即可访问的资源
    private static final List<String> EXCLUDED_PATHS = Arrays.asList(
            "/login.html",
            "/login",
            "/register.html",
            "/register",
            "/check-login",
            "/logout",
            "/documents.html",
            "/wechat-accounts.html",
            "/css/",
            "/js/",
            "/images/",
            "/fonts/",
            "/tailwindcss/",
            "/font-awesome/"
    );

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("SessionFilter 初始化");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        String path = httpRequest.getRequestURI();
        logger.debug("过滤请求路径: {}", path);
        
        // 检查是否是不需要登录的路径
        boolean isExcluded = false;
        for (String excludedPath : EXCLUDED_PATHS) {
            if (path.startsWith(excludedPath)) {
                isExcluded = true;
                break;
            }
        }
        
        // 静态资源也直接通过，但排除index.html
        if ((path.endsWith(".css") || path.endsWith(".js") || path.endsWith(".png") || 
            path.endsWith(".jpg") || path.endsWith(".jpeg") || path.endsWith(".gif") || 
            path.endsWith(".svg") || path.endsWith(".woff") || path.endsWith(".woff2") || 
            path.endsWith(".ttf")) && !path.equals("/index.html")) {
            isExcluded = true;
        }
        
        if (isExcluded) {
            // 不需要登录，直接放行
            chain.doFilter(request, response);
        } else {
            // 需要登录，检查会话
            HttpSession session = httpRequest.getSession(false);
            if (session != null && session.getAttribute("username") != null) {
                // 已登录，放行
                logger.debug("用户已登录，允许访问: {}", path);
                chain.doFilter(request, response);
            } else {
                // 未登录，重定向到登录页面
                logger.info("用户未登录，重定向到登录页面: {}", path);
                httpResponse.sendRedirect("/login.html");
            }
        }
    }

    @Override
    public void destroy() {
        logger.info("SessionFilter 销毁");
    }
}